<template>
  <el-form ref="loginFormRef" :model="formData" :rules="formRules" label-width="120px" size="large" class="login-form">
    <h2 class="form-title">用户登录</h2>

    <el-form-item label="手机号" label-position="top" prop="username">
      <el-input v-model="formData.username" placeholder="请输入手机号" prefix-icon="User" />
    </el-form-item>

    <el-form-item label="密码" label-position="top" prop="password">
      <el-input v-model="formData.password" placeholder="请输入密码" type="password" show-password prefix-icon="Lock" />
    </el-form-item>

    <el-form-item class="remember-item" label-position="top">
      <el-checkbox v-model="rememberMe">记住我</el-checkbox>
      <el-link type="primary" class="forgot-link" @click="goToRegister">没有账号？立即注册</el-link>
    </el-form-item>

    <el-form-item label-position="top">
      <el-button type="primary" class="submit-btn" @click="handleSubmit" :loading="loading">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import type { FormInstance, FormRules } from 'element-plus'
  import { login } from '@/api/userApi'
  import { useRouter } from 'vue-router'
  import { ElMessage } from 'element-plus'

  const router = useRouter()

  // 定义props用于接收预填充的账号
  const props = defineProps<{
    preFilledAccount?: string
  }>()

  // 添加加载状态
  const loading = ref(false)

  // 表单数据类型
  interface LoginForm {
    username: string
    password: string
  }

  // 表单引用
  const loginFormRef = ref<FormInstance>()

  // 表单数据
  const formData = reactive<LoginForm>({
    username: props.preFilledAccount || '',
    password: '',
  })

  // "记住我"状态
  const rememberMe = ref(false)

  // 表单验证规则
  const formRules = reactive<FormRules<LoginForm>>({
    username: [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { min: 11, max: 11, message: '手机号格式错误', trigger: 'blur' },
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 18, message: '密码长度应为6-18个字符', trigger: 'blur' },
    ],
  })

  // 加载保存的凭证
  onMounted(() => {
    console.log('加载保存的凭证...')
    if (props.preFilledAccount) {
      formData.username = props.preFilledAccount
      rememberMe.value = false
      localStorage.clear()
      console.log('填充手机号成功, 已清除上一位用户信息')
      return
    }

    const savedUsername = localStorage.getItem('account')
    const rememberMeFlag = localStorage.getItem('rememberMe') === 'true'

    if (savedUsername && rememberMeFlag) {
      formData.username = savedUsername
      rememberMe.value = true
    }
  })

  // 提交表单
  const handleSubmit = async () => {
    if (!loginFormRef.value) return

    const isValid = await loginFormRef.value.validate()
    if (!isValid) return

    loading.value = true

    try {
      // 触发登录逻辑
      await login(formData.username, formData.password)
      emit('submit', {
        username: formData.username,
        password: formData.password,
        rememberMe: rememberMe.value,
      })

      // 处理记住我逻辑
      if (rememberMe.value) {
        localStorage.setItem('account', formData.username)
        localStorage.setItem('rememberMe', 'true')
      } else {
        localStorage.removeItem('account')
        localStorage.removeItem('rememberMe')
      }
    } catch (error) {
      if (error instanceof Error) {
        // 密码错误时高亮密码字段
        if (error.message.includes('密码错误') && loginFormRef.value) {
          loginFormRef.value.validateField('password')
        }
        ElMessage.error({
          message: '手机号或密码错误',
          duration: 3000,
          showClose: true,
        })
      }
    } finally {
      loading.value = false
    }
  }

  // 定义事件
  const emit = defineEmits<{
    (e: 'submit', data: { username: string; password: string; rememberMe: boolean }): void
  }>()

  // 跳转到注册页面
  const goToRegister = () => {
    router.push('/register')
  }
</script>

<style scoped>
  .login-form {
    width: 80%;
    max-width: 480px;
    padding: 40px;
    border-radius: 12px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
    background: #fff;
  }

  .form-title {
    text-align: center;
    margin-bottom: 36px;
    color: #333;
    font-weight: 600;
  }

  .remember-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .forgot-link {
    margin-left: auto;
  }

  .submit-btn {
    width: 100%;
    height: 50px;
    font-size: 16px;
    margin-top: 10px;
  }
</style>
